import React from 'react';
import { withRouter } from 'react-router-dom';
import LogUtils from '@/utils/tools/log_utils';
import { PageProps } from '@/typings/react.type';

interface ErrorBoundaryState {
  hasError: boolean;
  error: string | null;
}

class ErrorBoundary extends React.Component<PageProps, ErrorBoundaryState> {
  constructor(props) {
    super(props);
    this.state = {
      hasError: false,
      error: null,
    };
  }

  componentDidUpdate(prevProps: PageProps) {
    if (this.props.location !== prevProps.location) {
      // 注入访问来源页面
      this.props.location.referrer = prevProps.location.pathname;
      // window.scrollTo(0, 0);
    }
  }

  componentDidCatch(error: any, info: any) {
    LogUtils.d('error', error);
    LogUtils.d('info', info);

    this.setState({
      hasError: true,
      error: String(error),
    });
  }

  render() {
    if (this.state.hasError) {
      return <div>错误:${this.state.error}</div>;
    }
    return this.props.children;
  }
}

export default withRouter(ErrorBoundary);
